package com.study.example.gameserver.module.currency.entity;

import com.sparrow.cache.annotation.Cache;
import com.sparrow.cache.annotation.CacheType;
import com.study.example.gameserver.module.currency.convert.IntegerLongMapConverter;
import com.study.example.gameserver.module.currency.domain.CurrencyType;
import com.study.example.gameserver.module.entity.PlayerData;

import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 玩家货币
 */
@Cache(cacheType = CacheType.NONE)
@Entity
@Table(name = "PlayerCurrency")
public class PlayerCurrency extends PlayerData {

    @Convert(converter = IntegerLongMapConverter.class)
    @Column(name = "data", columnDefinition = "LONGTEXT")
    private ConcurrentHashMap<Integer, Long> dataMap = new ConcurrentHashMap<>();

    public void setDataMap(ConcurrentHashMap<Integer, Long> dataMap) {
        this.dataMap = dataMap;
    }

    public ConcurrentHashMap<Integer, Long> getDataMap() {
        return dataMap;
    }

    /** 增加货币 */
    public void addCurrency(CurrencyType currencyType, long addValue) {
        if (addValue == 0) {
            return;
        }
        long old = dataMap.getOrDefault(currencyType.getType(), 0L);
        dataMap.put(currencyType.getType(), old + addValue);
        update(); // 标记数据更新
    }

    /** 获取货币数量 */
    public long getCurrency(CurrencyType currencyType) {
        return dataMap.getOrDefault(currencyType.getType(), 0L);
    }

    /** 检查余额是否足够 */
    public boolean hasEnough(CurrencyType currencyType, long needValue) {
        if (needValue <= 0) {
            return true;
        }
        long current = dataMap.getOrDefault(currencyType.getType(), 0L);
        return current >= needValue;
    }

    /** 扣除货币（余额不足返回false） */
    public boolean costCurrency(CurrencyType currencyType, long costValue) {
        if (costValue <= 0) {
            return true; // 扣0不处理
        }

        long current = dataMap.getOrDefault(currencyType.getType(), 0L);
        if (current < costValue) {
            return false; // 余额不足
        }

        dataMap.put(currencyType.getType(), current - costValue);
        update(); // 标记持久化
        return true;
    }
}
